package cn.xiehang.SoundSight;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ThirdFragment extends Fragment{
    List<Article> articles;
    RecyclerView recyclerView;
    String getArticleUrl = SeverURL.URL + "/get_article";
    String getMyArticleUrl = SeverURL.URL + "/get_my_article";
    ArticleAdapter adapter;
    TextView recommendTextView,myArticleTextView,noticeTextView;
    String state;
    public ThirdFragment() {
        // Required empty public constructor
    }
    public ThirdFragment(String state) {
        // Required empty public constructor
        this.state = state;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_third, container, false);
        recyclerView = view.findViewById(R.id.third_fragment_recycler_view);
        recommendTextView = view.findViewById(R.id.third_fragment_button_1);
        myArticleTextView = view.findViewById(R.id.third_fragment_button_2);
        noticeTextView = view.findViewById(R.id.third_fragment_notice);
        //设置点击事件
        noticeTextView.setOnClickListener(v -> {
          getNotice();
        }

        );
        recommendTextView.setOnClickListener(v -> {
            getArticles();
        });
        myArticleTextView.setOnClickListener(v -> {
            getMyArticles();
        });
        //设置布局，使用StaggeredGridLayoutManager来实现瀑布流效果
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(
                2, // 列数（左右两列）
                StaggeredGridLayoutManager.VERTICAL // 垂直排列
        );
//        adapter = new ArticleAdapter(new ArrayList<>()); // 初始为空列表




        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        if (state == null) {
            // 默认加载推荐文章
            getArticles();
        } else if (state=="myArticle") {
            // 加载我的文章
            getMyArticles();
        } else {
            // 默认加载推荐文章
            getArticles();
        }
        return view;
    }

    private void getNotice(){
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return ;
        }
        String username = sharedPref.getString("username", null);
        String password = sharedPref.getString("password", null);
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建请求体
        JSONObject json = new JSONObject();
        try {
            json.put("username", username);
            json.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }

        RequestBody requestBody = RequestBody.create(
                json.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );

        // 创建请求
        Request request = new Request.Builder()
                .url(SeverURL.URL + "/get_notice")  // 替换为实际服务器地址
                .post(requestBody)
                .build();

        // 异步发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireContext(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "服务器错误: " + response.code(), Toast.LENGTH_SHORT).show();
                    });
                    return;
                }

                try {
                    String responseData = response.body().string();
                    JSONObject jsonResponse = new JSONObject(responseData);

                    if (jsonResponse.has("error")) {
                        String error = jsonResponse.getString("error");
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(requireContext(), error, Toast.LENGTH_SHORT).show();
                        });
                        return;
                    }

                    JSONArray articlesJson = jsonResponse.getJSONArray("notices");
                    List<FAQItem>  noticeList= new ArrayList<>();

                    for (int i = 0; i < articlesJson.length(); i++) {
                        JSONObject noticeJson = articlesJson.getJSONObject(i);
                        String title = noticeJson.getString("公告标题");
                        String content = noticeJson.getString("公告内容");
                        FAQItem faqItem = new FAQItem(title, content);
                        noticeList.add(faqItem);
                    }

                    // 处理获取到的文章列表
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "获取公告成功", Toast.LENGTH_SHORT).show();
                        setNotice(noticeList);
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "数据解析错误", Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });


    }

    private void setNotice(List<FAQItem> noticeList) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View dialogView = getLayoutInflater().inflate(R.layout.fragment_notice, null);
        RecyclerView recyclerView1=dialogView.findViewById(R.id.notice_recycler_view);
        NoticeAdapter adapter = new NoticeAdapter(noticeList);
        recyclerView1.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView1.setAdapter(adapter);
        builder.setView(dialogView);

        AlertDialog dialog = builder.create();

        // 设置对话框大小
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);

        Button btnQuit = dialogView.findViewById(R.id.btnQuit);
        btnQuit.setOnClickListener(v -> {
            dialog.dismiss();
        });

        dialog.show();
    }

    public void onResume() {
        super.onResume();
        // 重新获取文章列表
        getArticles();
    }


    public void getArticles(){
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return ;
        }
        String username = sharedPref.getString("username", null);
        String password = sharedPref.getString("password", null);
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建请求体
        JSONObject json = new JSONObject();
        try {
            json.put("username", username);
            json.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }

        RequestBody requestBody = RequestBody.create(
                json.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );

        // 创建请求
        Request request = new Request.Builder()
                .url(getArticleUrl)  // 替换为实际服务器地址
                .post(requestBody)
                .build();

        // 异步发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireContext(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "服务器错误: " + response.code(), Toast.LENGTH_SHORT).show();
                    });
                    return;
                }

                try {
                    String responseData = response.body().string();
                    JSONObject jsonResponse = new JSONObject(responseData);

                    if (jsonResponse.has("error")) {
                        String error = jsonResponse.getString("error");
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(requireContext(), error, Toast.LENGTH_SHORT).show();
                        });
                        return;
                    }

                    JSONArray articlesJson = jsonResponse.getJSONArray("articles");
                    articles = new ArrayList<>();

                    for (int i = 0; i < articlesJson.length(); i++) {
                        JSONObject articleJson = articlesJson.getJSONObject(i);

                        // 解析作者信息
                        JSONObject authorJson = articleJson.getJSONObject("author");
                        User author = new User(
                                authorJson.getString("name"),
                                authorJson.getString("avatar_url"),
                                authorJson.getString("level")
                        );

                        // 创建文章对象
                        Article article = new Article(
                                articleJson.getInt("article_id"),
                                articleJson.getString("title"),
                                articleJson.getString("content"),
                                articleJson.getString("image"),  // 图片URL
                                articleJson.getString("audio"),  // 音频URL
                                author,
                                articleJson.getString("create_time"),
                                articleJson.optInt("thumbs_up_numbers"),
                                articleJson.optInt("collect_numbers"),
                                null  // comments - 服务器返回中没有此字段
                        );

                        // 设置是否有音频
                        // 这里假设如果音频URL不为空，则有音频
                        if (articleJson.getString("audio")!= "null") {
                            article.setHaveAudio(true);
                        } else {
                            article.setHaveAudio(false);
                        }

                        articles.add(article);
                    }

                    // 处理获取到的文章列表
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "获取文章成功", Toast.LENGTH_SHORT).show();

                        // 这里可以更新UI，例如将文章列表传递给Adapter
                        adapter= new ArticleAdapter(articles);
                        adapter.setOnItemClickListener(article -> {
                            changeFragment(article);
                        });
                        adapter.notifyDataSetChanged();
                        recyclerView.setAdapter(adapter);
                        recommendTextView.setTextSize(30);
                        myArticleTextView.setTextSize(25);
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "数据解析错误", Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }
    public void reClick(){
        getMyArticles();
    }
    public void getMyArticles(){
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return ;
        }
        String username = sharedPref.getString("username", null);
        String password = sharedPref.getString("password", null);
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建请求体
        JSONObject json = new JSONObject();
        try {
            json.put("username", username);
            json.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }

        RequestBody requestBody = RequestBody.create(
                json.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );

        // 创建请求
        Request request = new Request.Builder()
                .url(getMyArticleUrl)  // 替换为实际服务器地址
                .post(requestBody)
                .build();

        // 异步发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireContext(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "服务器错误: " + response.code(), Toast.LENGTH_SHORT).show();
                    });
                    return;
                }

                try {
                    String responseData = response.body().string();
                    JSONObject jsonResponse = new JSONObject(responseData);

                    if (jsonResponse.has("error")) {
                        String error = jsonResponse.getString("error");
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(requireContext(), error, Toast.LENGTH_SHORT).show();
                        });
                        return;
                    }

                    JSONArray articlesJson = jsonResponse.getJSONArray("articles");
                    articles = new ArrayList<>();

                    for (int i = 0; i < articlesJson.length(); i++) {
                        JSONObject articleJson = articlesJson.getJSONObject(i);

                        // 解析作者信息
                        JSONObject authorJson = articleJson.getJSONObject("author");
                        User author = new User(
                                authorJson.getString("name"),
                                authorJson.getString("avatar_url"),
                                authorJson.getString("level")
                        );

                        // 创建文章对象
                        Article article = new Article(
                                articleJson.getInt("article_id"),
                                articleJson.getString("title"),
                                articleJson.getString("content"),
                                articleJson.getString("image"),  // 图片URL
                                articleJson.getString("audio"),  // 音频URL
                                author,
                                articleJson.getString("create_time"),
                                articleJson.optInt("thumbs_up_numbers"),
                                articleJson.optInt("collect_numbers"),
                                null  // comments - 服务器返回中没有此字段
                        );

                        // 设置是否有音频
                        // 这里假设如果音频URL不为空，则有音频
                        if (articleJson.getString("audio")!= "null") {
                            article.setHaveAudio(true);
                        } else {
                            article.setHaveAudio(false);
                        }

                        articles.add(article);
                    }

                    // 处理获取到的文章列表
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "获取文章成功", Toast.LENGTH_SHORT).show();

                        // 这里可以更新UI，例如将文章列表传递给Adapter
                        adapter= new ArticleAdapter(articles);
                        adapter.setOnItemClickListener(article -> {
                            changeFragment(article);
                        });
                        adapter.notifyDataSetChanged();
                        recyclerView.setAdapter(adapter);
                        myArticleTextView.setTextSize(30);
                        recommendTextView.setTextSize(25);
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "数据解析错误", Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }
    private void changeFragment(Article article){
        FragmentActivity activity = getActivity();
        if (activity != null) {
            FragmentManager fm = activity.getSupportFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            // 隐藏所有Fragment
            for (Fragment frag : fm.getFragments()) {
                if (frag != null && frag.isAdded()) {
                    transaction.hide(frag);
                }
            }
            Fragment existingFragment = fm.findFragmentByTag("ArticleFragment");

            if (existingFragment != null) {
                ((ArticleFragment) existingFragment).reclick(article);
                transaction.show(existingFragment);
            } else {
                Fragment articleFragment = new ArticleFragment();
                ((ArticleFragment) articleFragment).setArticle(article);
                transaction.add(R.id.FragmentContainer, articleFragment, "ArticleFragment");
            }
            transaction.commit();
        }
    }

    public static ThirdFragment newInstance() {
        return new ThirdFragment();
    }


}
